package com.ruoyi.framework.interceptor;

import cn.hutool.core.collection.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.regex.Pattern;

/**
 * @author liutao
 * @version 1.0
 * @description: TODO
 * @date 2024/6/14 15:52
 */
@Slf4j
@Component
public class ResourceInterceptor implements HandlerInterceptor {

    /**
     * 令牌自定义标识
     */
    @Value("${token.header}")
    private String header;

    /**
     * 匹配的文件种类
     */
    private static final String FILE_REGEX = "\\.(html|css|js|jpg|jpeg|png|gif|bmp|svg|pdf|doc|docx|xls|xlsx|ppt|pptx|mp4|mov)$";
    private static final Pattern FILE_REGEX_PATTERN = Pattern.compile(FILE_REGEX, Pattern.CASE_INSENSITIVE);


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求的 URL
        String requestUrl = request.getRequestURL().toString();
        // 检查是否是静态资源请求
        if (isStaticResource(requestUrl)) {
            log.info("requestUrl:{}", requestUrl);
            log.info("request token:{}", request.getHeader(header));
//            // 检查防盗链策略
//            if (!isValidReferer(request)) {
//                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
//                return false;
//            }
        }
        return true;
    }

    /**
     * 正则验证请求的资源
     *
     * @param url 请求资源
     * @return 是否匹配
     */
    private boolean isStaticResource(String url) {
        return FILE_REGEX_PATTERN.matcher(url).find();
    }

    /**
     * 检查 Referer 头，判断请求是否合法
     *
     * @param request 请求
     * @return 是否是合法请求
     */
//    private boolean isValidReferer(HttpServletRequest request) {
//        String referer = request.getHeader(header);
//        return CollectionUtil.contains(referConfig.getAllowedOrigins(), referer);
//    }
}
